package org.example.common.valid;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class ValidInterceptor implements HandlerInterceptor {

//    @Autowired
//    private ParamValidFactory paramValidFactory;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 确保请求已被包装
        if (request instanceof RequestWrapper) {
            RequestWrapper wrappedRequest = (RequestWrapper) request;
            String body = wrappedRequest.getBody();

            if (body != null && !body.isEmpty()) {
                try {
                    // 解析JSON获取code值
                    JSONObject jsonObject = JSONObject.parseObject(body);
                    String code = jsonObject.getString("code");
                    System.out.println("拦截器中获取的code: " + code);

                    // 可将code存入request，供后续使用
                    request.setAttribute("requestCode", code);
                } catch (Exception e) {
                    // 处理解析异常
                    return true; // 不中断请求，仅记录日志
                }
            }
        }

        return true; // 放行请求
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
